import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import type { UserInfoState } from "./interface";
import { ElMessage } from "element-plus";
import { staticRoutes } from "@/router/routes";
import { reqLogin, reqLogout, reqUserInfo } from "@/api/user";

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserInfoState => ({
    token: getToken() as string,
    userInfo: {
      routes: [],
      buttons: [],
      roles: [],
      name: "",
      avatar: "",
    },
    menuRoutes: [],
  }),

  actions: {
    /* login (username: string, password: string) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          if (username==='admin' && password==='111111') {
            const token = 'token-atguigu'
            setToken(token)
            this.token = token
            resolve(token)
          } else {
            reject(new Error('用户名或密码错误!'))
            ElMessage.error('用户名或密码错误!')
          }
        }, 1000)
      })
    }, */

    async login(username: string, password: string) {
      try {
        //发送请求 请求token
        const result = await reqLogin({ username, password });
        //本地化存储
        setToken(result.token);
        //设置当前token
        this.token = result.token;
      } catch (e) {
        return Promise.reject(e);
      }
    },

    /* getInfo() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          this.name = "admin";
          this.avatar =
            "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif";
          this.menuRoutes = staticRoutes;
          resolve({ name: this.name, avatar: this.avatar, token: this.token });
        }, 1000);
      });
    }, */

    async getInfo() {
      /* 一定要去拦截器中配置携带token */
      try {
        //请求用户信息
        const result = await reqUserInfo();
        this.userInfo = result;
        //一定要把路由表也赋值给menuRoutes,方便sidebar生成菜单
        this.menuRoutes = staticRoutes;
      } catch (e) {
        return Promise.reject(e);
      }
    },
    
    async logout(){
      try {
        await reqLogout()
        this.reset()
      } catch (e) {
        return Promise.reject(e)
      }
    },
    reset() {
      // 删除local中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.token = "";
      this.userInfo.name = "";
      this.userInfo.avatar = "";
    },
  },
});
